import time

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app


class EntranceCounter(db.Model):
    """Models an individual Guestbook entry with an author, content, and date."""
    counter = db.IntegerProperty()
    last_entrance = db.DateTimeProperty(auto_now_add=True)
  
class EntranceDetails(db.Model):
    """Models an individual Guestbook entry with an author, content, and date."""
    author = db.StringProperty()
    condition_type = db.StringProperty()
    donation_per_day = db.FloatProperty()
    debt_total = db.FloatProperty()
    debt_today = db.FloatProperty()
    max_seconds_per_day = db.IntegerProperty()


class User():
    CONDS = ["MAX_SECONDS_PER_DAY"]

    @staticmethod
    def get_today():
        return str(time.localtime()[0]) + "-" + str(time.localtime()[1]) + "-" + str(time.localtime()[2])
    
    @staticmethod
    def get_day(user):
        return str(user.last_entrance)[:10]
    
    @staticmethod
    def set_user_counter(user):
        user.put()
        
    @staticmethod
    def get_user_counter(uid):
        tmpSTR = "SELECT * FROM EntranceCounter WHERE ANCESTOR IS KEY ('%s' , '%s')" %("EntranceCounter", uid)
        userEntrance = db.GqlQuery(tmpSTR)
        return userEntrance.get()
    
    @staticmethod
    def get_user_details(uid):
        tmpSTR = "SELECT * FROM EntranceDetails WHERE ANCESTOR IS KEY ('%s' , '%s')" %("EntranceDetails", uid)
        details = db.GqlQuery(tmpSTR).get()
        return details
        
    @staticmethod
    def get_user_debt(uid):
        user_details = User.get_user_details(uid)
        if not user_details:
            return 0
        return user_details.debt_total+user_details.debt_today
        
    @staticmethod
    def update_user(uid, extra_seconds):
        current_user = User.get_user_counter(uid)
        details = User.get_user_details(uid)
        
        if details != None:
            if current_user != None:
                if details.condition_type=="MAX_SECONDS_PER_DAY":
                    print User.get_day(current_user)
                    print User.get_today()
                    if User.get_day(current_user) == User.get_today():
                        if current_user.counter + extra_seconds > details.max_seconds_per_day:
                            current_user.donation_total = current_user.donation_total + current_user.donation_per_day
                        else:
                            current_user.counter = current_user.counter + extra_seconds
                            User.set_user_counter(current_user)
                    else:
                        current_user.counter = extra_seconds
                        User.set_user_counter(current_user)
                else: 
                    pass #raise error of missing data in EntranceCounter
            else:
                raise Int(1) #raise error of missing data in EntranceDetails
    
    @staticmethod
    def new_user(uid, name, cond_type, sum, seconds_per_day):
        #validate data
        newUser = EntranceDetails(key_name = uid, author=name, condition_type=cond_type, donation_per_day=sum, donation_total=0.0 ,
            did_donate_today="false", max_seconds_per_day=seconds_per_day)
        newUser.put()
        
        newCounter = EntranceCounter(key_name = uid, counter=0)
        newCounter.put()
    

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        User.new_user("noam1234", "noam", "MAX_SECONDS_PER_DAY", 5.99, 60)
        User.update_user("noam1234", 3)
        User.new_user("1","Lital","MAX_SECONDS_PER_DAY", 5.99, 60)
        User.update_user("1", 300)
        self.response.out.write('Hello from noam!')

class UpdateUserPage(webapp.RequestHandler):
    def get(self):
        print "UpdateUserPage.get"
        self.response.headers['Content-Type'] = 'text/html'
        
        if not self.request.get('user') or not self.request.get('secs'):
            print "no user or seconds given"
            self.response.out.write("please enter a user ane secs: /update?user=username&secs=30")
            return
                                     
        username = self.request.get('user')
        try:
            seconds = int(self.request.get('secs'))
        except:
            seconds = -1
          
        if seconds <= 0:
            print "seconds should be an integer bigger than 0"
            self.response.out.write("seconds should be bigger than 0, and not %s" % seconds)
            return
   
        print ("<html><body><p>user %s used up %d seconds</p></body></html>" % 
                           (username, seconds))
    
        return_val = User.update_user(username, seconds)
        self.response.out.write("<html><body><p>method returned %s</p></body></html>" % return_val)
    
class PayPage(webapp.RequestHandler):
    def get(self):
        print "PayPage.get"
        self.response.headers['Content-Type'] = 'text/html'
        if not self.request.get('user'):
            print "no user given"
            self.response.out.write("please enter a user ane secs: /update?user=username&secs=30")
            return
                   
        user_id = self.request.get('user')
        dept = User.get_user_debt(user_id)
        self.response.out.write("<html><body><p>You Owe:%d dollars, click here to pay </p></body></html>" %
                                dept)
        #call the method of paying with user_id, amount, random number for redirect back
    
class PostPayPage(webapp.RequestHandler):
    def get(self):
        print "PostPayPage.get"
        self.response.headers['Content-Type'] = 'text/html'
        #need to update the amount paid 
        self.response.out.write('Thanks for paying')

print "hello"
app = webapp.WSGIApplication([('/', MainPage),
                              ('/update', UpdateUserPage),
                              ('/pay', PayPage),
                              ('/postpay', PostPayPage)
                              ],
                              debug=True)
